package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"short-vid-joy/models/cache"
	"short-vid-joy/models/mysql"
	"time"

	"short-vid-joy/shortrpc/internal/svc"
	"short-vid-joy/shortrpc/shortrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVideoListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoListLogic {
	return &VideoListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *VideoListLogic) VideoList(in *shortrpc.VideoListRequest) (*shortrpc.VideoListResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User

	if err := findUser.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}

	var videoList []*shortrpc.VideoList

	key := fmt.Sprintf("list%d_%d", in.Page, in.PageSize)

	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		videoList = mysql.VideoList(mysql.DB, in, videoList)

		marshal, _ := json.Marshal(videoList)

		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*10)
	} else {
		json.Unmarshal([]byte(result), &videoList)
	}

	return &shortrpc.VideoListResponse{
		List: videoList,
	}, nil
}
